package org.project.exception;

import lombok.extern.slf4j.Slf4j;
import org.project.utils.Result2;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

/**
 * @Auther: hzy
 * @Date: 2022/4/11
 * @Description: 全局异常处理
 * 处理整个web controller的异常
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    //处理校验异常，对于对象类型的数据的校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result2<Object> handler(MethodArgumentNotValidException e) {
        StringBuffer sb = new StringBuffer();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        allErrors.forEach(msg -> sb.append(msg.getDefaultMessage()).append(";"));
        return new Result2<>(false, sb.toString(), null);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Result2<Object> handler(ConstraintViolationException e) {
        StringBuffer errorMsg = new StringBuffer();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        violations.forEach(x -> errorMsg.append(x.getMessage()).append(";"));
        return new Result2<>(false, errorMsg.toString(), null);
    }

    @ExceptionHandler(Exception.class)
    public Result2<Object> handleException(Exception e) {
        log.error("异常是：{}", e.toString());
        return new Result2<>(false, e.getMessage(), null);
    }


}
